import classnames from 'classnames'
import './index.scss'
import {useState, useRef, MouseEvent, ReactNode} from "react";
import Icon from '../Icon'

export interface ButtonProps {
  text?: string,
  block?: boolean,
  danger?: boolean,
  disabled?: boolean,
  ghost?: boolean,
  href?: string,
  htmlType?: 'button' | 'submit' | 'reset',
  icon?: ReactNode,
  loading?: boolean,
  shape?: 'default' | 'circle' | 'round',
  size?: 'large' | 'middle' | 'small',
  target?: string,
  type?: 'default' | 'primary' | 'ghost' | 'dashed' | 'link' | 'text',
  onClick?: (event: MouseEvent) => void,
  children?: string,
  className?: string
}


export default function Button(props: ButtonProps) {
  const {
    loading = false,
    type = 'default',
    icon,
    disabled = false,
    danger,
    size = 'middle',
    onClick,
    className
  } = props

  const [shadows, setShadows] = useState<any[]>([])
  const shadowsRef = useRef<any[]>([])
  const cur = useRef(0)

  const _disabled = loading || disabled

  const cls = classnames('button', type, size, {
    disabled: _disabled,
    danger: danger
  }, className)

  function clickHandler(e: MouseEvent<HTMLButtonElement>) {
    if (loading) {
      e.preventDefault();
      return;
    }

    cur.current = cur.current + 1
    const curEvent: any = { key: cur.current }

    curEvent.timer = setTimeout(() => {
      shadowsRef.current = shadowsRef.current.filter((item) => item.key !== curEvent.key)
      setShadows([...shadowsRef.current])
      clearTimeout(curEvent.timer)
    }, 2000)

    shadowsRef.current = [curEvent, ...shadowsRef.current]
    setShadows([...shadowsRef.current])

    onClick && onClick(e)
  }
  const iconNode = icon ? icon : null
  const insertNode = loading ? <Icon type="loading" /> : iconNode

  return (
    <button className={cls} onClick={clickHandler} disabled={_disabled}>
      {shadows.map(item => (
        <div key={item.key} className="shadow"></div>
      ))}
      {insertNode}
      {props.children && <span>{props.children}</span>}
    </button>
  )
}
